<template>
    <view class="content df fdc">
        <view class="map-main f1">
            <view id="DzMap" :prop="sender" :change:prop="renderMaps.handleAction"></view>
            <view class="map-control">
                <view class="zoom">
                    <view class="plus" @click="renderMaps.zoomIn">
                        <image src="@/static/img/map/jia.svg" class="icon" />
                    </view>
                    <view class="reduce" @click="renderMaps.zoomOut">
                        <image src="@/static/img/map/jian.svg" class="icon" />
                    </view>
                </view>
                <!-- <view class="location df fdc ac" @click="goOrBackLocation">
					<image src="@/static/img/map/dingwei.svg" class="icon" />
					<view class="desc" v-if="nowView == 0">定位</view>
					<view class="desc" v-else>复位</view>
				</view> -->
            </view>
        </view>

        <view class="top-box jsa">
            <uv-button type='primary' :disabled="area === '3' ? false : true"
                v-if="(spshow == 1 || spshow == 9) ? true : false" @click="toReport">信息上报<text class="noPermissions">{{
                    area !== '3' ? '( 您没有操作权限 )' : '' }}</text></uv-button>

            <uv-button type='error' color="red" v-if="spshow == 0 ? true : false" @click="gotoList(1)">待批示列表</uv-button>
            <uv-button type="success" @click="gotoList(0)">历史信息</uv-button>
        </view>

        <uv-popup ref="featurePopupZqd" mode="bottom" closeable @change="renderMaps.handleFeaturePopupClose">
            <view class="top-box-popup">
                <view>{{ danType }}</view>
            </view>
            <view class="p-20">
                <uv-form :model="popupInfo" label-width="160rpx" :labelStyle="{ fontSize: '28rpx' }">
                    <uv-form-item label="时间:" borderBottom>
                        {{ popupInfo.Fssj && popupInfo.Fssj.replace("T", " ") }}
                        <!-- <uv-input v-model="popupInfo.name" readonly border="none" /> -->
                    </uv-form-item>
                    <uv-form-item label="填表人:" borderBottom>
                        {{ popupInfo.Tbr }}
                        <!-- <uv-input v-model="popupInfo.code" readonly border="none" /> -->
                    </uv-form-item>
                    <uv-form-item label="地址:" borderBottom>
                        {{ popupInfo.Province + popupInfo.City + popupInfo.District + popupInfo.Town }}
                        <!-- <uv-input v-model="popupInfo.site" readonly border="none" /> -->
                    </uv-form-item>
                </uv-form>
                <view class="btn-box">
                    <uv-button color="#1f87c6" @click="viewItem">详情信息</uv-button>
                </view>
            </view>
        </uv-popup>
    </view>

</template>
<!-- 逻辑层 -->
<script>
import { SYSFORMOPERTYPE } from '@/utils/enum'
import { getLoginMsg } from '@/utils/util'
import { GetMapData_API, GetZqsbDetail_API } from '@/server/home'
export default {
    data() {
        return {
            nowView: 0,
            sender: {
                handle: '',//调用视图层方法的名字
                callback: '',//回调函数的名字
                options: null,//传递给视图层的数据
                AdminCode: getLoginMsg()?.AdminCode,
            },
            area: '3',
            SYSFORMOPERTYPE: SYSFORMOPERTYPE,
            spshow: getLoginMsg()?.UserType,
            popupInfo: {},
            danType: ''
        };
    },
    created() {
        // this.$eventBus.$on('refresh-data', () => {
        // 	console.log('$eventBus', 'disaster-dcpj');
        // 	this.drawPoint();
        // });
    },
    // onLoad(option) {
    // this.drawPoint();
    // this.getLocation();
    // },
    onShow() {
        this.drawPoint();
        // this.getBtnRole()
        // this.spshow
        console.log("🚀 ~ onShow ~ this.spshow:", this.spshow)
    },
    mounted() {
    },
    methods: {
        /**
         * 逻辑层传递数据到视图层 类似父传子
         *
         * @param handle 触发视图层的方法名称
         * @param callback 视图层的方法名称（可选）暂时无用
         * @param options 消息发送的配置选项
         * @param rendCallback 逻辑层的回调函数（可选）暂时无用
         */
        sendMsg(handle, callback, options, rendCallback) {
            this.sender = {
                handle,
                options,
                callback,
                rendCallback
            }
        },
        /**
           * 视图层触发逻辑层方法 类似子传父
           * @param event callback 逻辑层的方法名称
           * @param event param 传递给逻辑层的数据
           */
        handleItemClick(event) {
            const handle = this[event.callback];
            handle && handle(event.param);
        },
        goOrBackLocation() {
            if (this.nowView === 0) {
                uni.showLoading({
                    title: '定位中...'
                });
                // #ifdef APP-PLUS
                plus.geolocation.getCurrentPosition(
                    (res) => {
                        const { latitude, longitude } = res.coords;
                        this.sendMsg('handlegoOrBackLocation', '', { type: 0, latitude, longitude })
                    }, (error) => {
                        console.error('Error getting location:', error.message);
                    }
                )
                // #endif
                // #ifdef H5
                navigator.geolocation.getCurrentPosition(
                    (res) => {
                        const { latitude, longitude } = res.coords;
                        this.sendMsg('handlegoOrBackLocation', '', { type: 0, latitude, longitude })
                    }, (error) => {
                        console.error('Error getting location:', error.message);
                    }
                )
                // #endif
                this.nowView = 1
                setTimeout(() => {
                    uni.hideLoading();
                }, 1000)
            } else {
                this.sendMsg('handlegoOrBackLocation', '', { type: 1 })
                this.nowView = 0
            }
        },
        // 获取登录者的按钮权限
        // getBtnRole() {
        //     if (this.token) {
        //         const par = {
        //             url: this.api.subBtn,
        //             type: 'get'
        //         }
        //         this.request(par).then(res => {
        //             if (res.code === 0) {
        //                 this.area = res.data.areaLeve
        //             }
        //         })
        //     }
        // },
        // 点击上报灾险情
        toReport() {
            uni.navigateTo({
                url: '/pages/home/disasterReportSimple?optype=' + SYSFORMOPERTYPE.Add
            })
        },
        gotoList(type) {
            uni.navigateTo({
                url: `/pages/home/disasterList?optype=${type}`
            })
        },
        async drawPoint() {
            let type = 4;
            const res = await GetMapData_API()
            if (res.Data && res.Data.length > 0) {
                console.log("打点数据", res);
                let obj = {};
                obj.type = type;
                obj.data = res.Data;
                this.sendMsg("drawPointMap", null, JSON.stringify(obj));
            } else {
                console.log("无数据," + type);
                let obj = {};
                obj.type = type;
                obj.data = [];
                this.sendMsg("drawPointMap", null, JSON.stringify(obj));
            }
        },
        async handleFeaturePopup(e) {
            this.danType = e.type;
            const data = JSON.parse(e.data);
            const res = await GetZqsbDetail_API(data.Id)
            if (res.StatusCode == 0 && res.IsSuccess) {
                console.log("res.Data:", res.Data);
                this.popupInfo = res.Data;
                this.$refs.featurePopupZqd.open();
            }
        },
        viewItem() {
            uni.navigateTo({
                url: '/pages/home/disasterReportSimple1?optype=' + SYSFORMOPERTYPE.View + '&id=' + this.popupInfo.Id
            });
        }
    },
}
</script>

<!-- 视图层 -->
<script module="renderMaps" lang="renderjs">
import DzMap from "@/map/index";
import { getCityCode } from '@/map/json/district'
import Point from 'ol/geom/Point';
import Feature from 'ol/Feature';
import { Style } from "ol/style";
import Icon from "ol/style/Icon";
import { Select } from "ol/interaction";
let map = null;
let mapLhJson = null
let selectInteraction = null
export default {
	data() {
		return {
			AdminCode:'430524',
			currentType:undefined,
			zxqMarkerLayerGroup: undefined,
		};
	},
	mounted() {
		this.initMap();
		this.addSingleClick()
	},
	methods: {
		handleAction(newValue, oldValue, ownerInstance, instance){
			console.log('逻辑层传递过来的数据', newValue)
      		const handle = this[newValue.handle]
      		let options = newValue.options
      		// this.callback = newValue.callback
      		if (!options) {
				options = undefined
			}
			if (!handle) {
				console.info('参数为标记需要执行的方法')
				return
			}
      		handle(options)
		},
		initMap() {
			map = new DzMap("DzMap");
			this.AdminCode = this.sender.AdminCode || '430524';
			mapLhJson = getCityCode(this.AdminCode);
			let features = map.format.converGeoJsonToFeature(mapLhJson.data);
			let geom = features[0].getGeometry();
			map.layer.initLayer(geom);
			// 更换层级
			let extent = geom.getExtent()
			map.map.getView().fit(extent, {
				duration: 0,//过渡时间
				padding: [10, 10, 10, 10]
			})
			map.layer.addLayers("定位", 12)
			// 添加隐患点图层
			map.layer.addLayers("灾情点", 12)
		},
		zoomIn() {
			let zoom = map.view.getZoom() + 1;
			map.view.animate({
				duration: 250,
				zoom,
			});
		},
		zoomOut() {
			let zoom = map.view.getZoom() - 1;
			map.view.animate({
				duration: 250,
				zoom,
			});
		},

		// 用户视图切换
		handlegoOrBackLocation(event) {
			if (event.type == 0) {
				const { latitude, longitude } = event;
				let geoJson = {
					"type": "FeatureCollection",
					"features": []
				}
				let feature = {
					type: "Feature",
					properties: {
						title: "用户坐标点"
					},
					geometry: {
						type: "Point",
						coordinates: [Number(longitude), Number(latitude)]
					}
				}
				geoJson.features.push(feature)
				// 转化为ol要素
				let features = map.format.converGeoJsonToFeature(geoJson)
				map.layer.addGenralPoint(features, "定位")
				// 设置样式
				map.layer.setLayerIconStyle("定位", 'https://env-00jxt6hwsqjo.normal.cloudstatic.cn/lhmap/map/position.svg', .5)
				// 视图切换
				map.view.animate({
					center: [longitude, latitude],
					zoom: 12,
					duration: 1000
				})
			} else {
				let features = map.format.converGeoJsonToFeature(mapLhJson.data);
				let geom = features[0].getGeometry();
				// 更换层级
				let extent = geom.getExtent()
				map.map.getView().fit(extent, {
					duration: 0,//过渡时间
					padding: [10, 10, 10, 10]
				})
			}
		},
		drawPointMap(newValue){
			if (newValue === '' || newValue === undefined || newValue === null) return
			console.error("drawPointMap--------------------------------")
			let obj = JSON.parse(newValue)
			const { data, type } = obj;
			this.currentType = obj.type;
			if(data == null){
			    if (this.zxqMarkerLayerGroup != undefined) {
			    	// 清空图层源中的所有要素
			    	this.zxqMarkerLayerGroup.getSource().clear();
			    }
		    }else{
                const pointList = []
				for(let i = 0; i < data.length; i++) {
					const item = data[i]
					if(item.AdminCode.includes(this.AdminCode) !== -1){
						const point = [Number(item.Lon), Number(item.Lat)]
						const featurePoint = new Feature({
          				  geometry: new Point(point),
          				  ...item,
						  type:'灾情点'
          				})
          				pointList.push(featurePoint)
					} 
				}
				// 获取图层
 				const layer = map.layer.getLayerByName('灾情点')
				// 1. 设置图层样式函数
  				layer.setStyle(new Style({
						image: new Icon({
        				  src: 'https://env-00jxt6hwsqjo.normal.cloudstatic.cn/lhmap/map/suibaodian.svg',
        				  scale: 0.5,
        				})
					})
				)
				const source = layer.getSource()
				source.clear()
  				source.addFeatures(pointList)
		    }
		},
		/**
		 * 添加单点点击事件
		 */
		addSingleClick() {
			// 获取所有允许点击的图层
			const layer = map.layer.getLayerByName('灾情点')
			let allowedLayers = []
			// 创建选择交互
			selectInteraction = new Select({
				layers: [layer],
				style: null,
				// 添加点击容差，提高点击体验
				tolerance: 5
			})
			// 添加到地图
			map.map.addInteraction(selectInteraction)
			// 监听选中事件
			selectInteraction.on('select', (e) => {
				const feature = e.selected[0]
				if (feature) {
					const params = feature.getProperties()
					//触发逻辑层 handleFeaturePopup方法，并把参数传递过去
					this.$ownerInstance.callMethod('handleItemClick', {
						callback: 'handleFeaturePopup',
						param: {
							data: JSON.stringify(params),
							type: feature.get('type')
						}
					})
				}
			})
		},
		handleFeaturePopupClose() {
			console.log('清空选中状态')
			// 清空选中状态
			selectInteraction.getFeatures().clear()
		},
	}
}
</script>
<style>
page {
    height: 100%;
}
</style>
<style lang="scss" scoped>
.content {
    width: 100%;
    height: 100%;

    .map-main {
        position: relative;
    }

    #DzMap {
        width: 100%;
        height: 100%;
    }

    .map-control {
        .zoom {
            position: absolute;
            top: 20rpx;
            left: 20rpx;
            padding: 10rpx;
            background-color: #fff;
            border-radius: 6rpx;

            .plus {
                padding-bottom: 6rpx;
                border-bottom: 1px solid gray;
            }

            .reduce {
                padding-top: 6rpx;
            }
        }

        .location {
            width: 70rpx;
            padding: 6rpx;
            font-size: 24rpx;
            color: #1296db;
            position: absolute;
            bottom: 20rpx;
            left: 20rpx;
            background-color: #fff;
            border-radius: 6rpx;
        }

        .layer-choose {
            position: absolute;
            right: 20rpx;
            bottom: 20rpx;
            background: #fff;
            width: 70rpx;
            padding: 6rpx;
            font-size: 24rpx;
            color: #1296db;
            border-radius: 6rpx;
        }

        .search {
            position: absolute;
            top: 20rpx;
            padding: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60%;
            height: 50rpx;
            border-radius: 10rpx;
            background-color: #fff;
            text-align: center;
            color: #999;
            font-size: 26rpx;
        }

        .icon {
            display: block;
            width: 40rpx;
            height: 40rpx;
        }
    }

    .layer-popup {
        padding: 20rpx;

        h3 {
            margin-bottom: 20rpx;
            text-align: center;
        }

        .up {
            .item {
                margin-bottom: 20rpx;
            }

            image {
                width: 100rpx;
                height: 100rpx;
                border-radius: 50%;
                display: flex;
                flex-direction: column;
                align-items: center;
            }
        }

    }
}

.top-box {
    padding: 20rpx;
    border-top: solid 2rpx #D8D8D8;
    border-bottom: solid 2rpx #D8D8D8;
    display: flex;
}

.top-box-popup {
    display: flex;
    padding: 20rpx;
    color: #ffffff;
    font-size: 28rpx;
    font-weight: bold;
    background-color: #1f87c6;
    justify-content: space-between;
}

.p-20 {
    padding: 20rpx;
}

.btn-box {
    margin-top: 20rpx;
    display: flex;
    justify-content: space-around;
}
</style>